<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">

          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="100px">
            <el-form-item label="关键字" prop="name">
              <!-- <el-input v-model="queryParams.enableMark" placeholder="请输入是否完成" clearable
                @keyup.enter.native="handleQuery" /> -->
              <!-- <el-input v-model="queryParams.name" placeholder="请输入任务名" clearable @keyup.enter.native="handleQuery" /> -->
              <el-input v-model="name" placeholder="请输入任务名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="预计完成时间" prop="dateTime">
              <el-date-picker v-model="queryParams.dateTime" value-format="yyyy-MM-dd" type="daterange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="是否完成" prop="enableMark">
              <!-- <el-input v-model="queryParams.enableMark" placeholder="请输入是否完成" clearable
                @keyup.enter.native="handleQuery" /> -->
              <el-select v-model="queryParams.enableMark" placeholder="是否完成" clearable style="width: 120px"
                @keyup.enter.native="handleQuery">
                <el-option v-for="dict in dict.type.sys_complete" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['system:duty:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['system:duty:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['system:duty:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['system:duty:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-tree :data="dutyList" :props="defaultProps" @node-click="selectFile" highlight-current ref="tree" :filter-node-method="filterNode">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <!-- <div style="max-width: 228px; white-space: break-spaces;">{{ node.label }}</div> -->
              <el-tooltip class="item" effect="dark" :content="node.label" placement="top">
                <span>{{ (node.label).substring(0, 15) }}</span>
              </el-tooltip>
              <span>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(data)"
                  v-hasPermi="['system:duty:edit']">修改</el-button>
                <!-- <el-button size="mini" type="text" icon="el-icon-edit" v-if="!data.accept" @click="acceptDuty(data)"
                  v-hasPermi="['system:duty:edit']">接受</el-button> -->
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(data)"
                  v-hasPermi="['system:duty:remove']">删除</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span @click.stop="setEnableMark(data)" :style="{ color: data.enableMark == 1 ? 'green' : 'red' }">
                  <dict-tag size="mini" :options="dict.type.sys_complete" style="display: inline-block;margin-left: 20px;"
                    :value="data.enableMark" /></span>

                <!-- <el-button type="text" size="mini" @click="() => append(data)">
                  接受
                </el-button>
                <el-button type="text" size="mini" @click="() => remove(node, data)">
                  Delete
                </el-button> -->
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>任务文件</span>
            <!-- <el-input v-model="queryParamsFile.name" placeholder="请输入文件名" clearable @keyup.enter.native="handleQuery" /> -->

            <el-select ref="selectTree" v-model="queryParamsFile.deptId" placeholder="上传部门" clearable
              style="width: 120px;margin-left: 100px;">

              <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId">
              </el-option>
            </el-select>&nbsp;&nbsp;&nbsp;&nbsp;
            <el-button style=" padding: 3px 0;margin-left: 50px;" type="text" @click="searchFile()">搜索</el-button>
            <el-button style="float: right; padding: 3px 0" type="text" @click="uploadFile()">上传文件</el-button>
          </div>
          <el-table v-loading="loading" :data="fileAcceptList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="${comment}" align="center" prop="id" /> -->
            <el-table-column label="文件名" align="center" prop="fileName" />
            <el-table-column label="上传时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上传部门" align="center" prop="deptName" />
            <el-table-column label="上传人" align="center" prop="userName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="downFile(scope.row)"
                  v-hasPermi="['system:duty:down']">下载</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteFile(scope.row)"
                  v-hasPermi="['system:duty:remove']" v-if="userId==scope.row.createUser">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card><br>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>任务说明</span>
            <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
          </div>
          {{ dutyDescription }}
        </el-card><br>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>相关附件</span>
          </div>
          <el-table v-loading="loading" :data="fileDutyList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="${comment}" align="center" prop="id" /> -->
            <el-table-column label="文件名" align="center" prop="fileName" />
            <!-- <el-table-column label="上传人" align="center" prop="createUser" /> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="downFile(scope.row)"
                  v-hasPermi="['system:duty:edit']">下载</el-button>
                <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:duty:remove']">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="formDia" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上级任务" prop="parentId">
          <el-select ref="selectTree" v-model="form.parentId" placeholder="上级任务" clearable style="width: 120px">

            <el-option v-for="item in dutyListOption" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务名" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名" />
        </el-form-item>
        <el-form-item label="可见部门" prop="deptIdList">
          <!-- <el-input v-model="form.name" placeholder="请输入任务名" /> -->
          <el-select ref="selectTree" v-model="form.deptIdList" multiple placeholder="可见部门" clearable
            style="width: 120px">

            <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否完成" prop="enableMark">
          <el-select v-model="form.enableMark" placeholder="是否完成" clearable style="width: 120px">
            <el-option v-for="dict in dict.type.sys_complete" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预计完成时间" prop="completeTime">
          <el-date-picker clearable v-model="form.completeTime" style="width: 100%;" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择预计完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务说明" prop="remark">
          <!-- <el-date-picker clearable v-model="form.remark" type="date" value-format="yyyy-MM-dd" placeholder="请选择预计完成时间">
          </el-date-picker> -->
          <el-input type="textarea" style="width: 100%;" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
            v-model="form.remark">
          </el-input>
        </el-form-item>

        <el-form-item label="相关附件" prop="completeTime">
          <el-upload ref="uploadDuty" :limit="1" :action="uploadDuty.url" :headers="uploadDuty.headers"
            :file-list="uploadDuty.fileList" :on-progress="handleFileUploadProgress" :on-success="handleDutySuccess"
            :auto-upload="false" :on-remove="handleRemove">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading"
              @click="submitDutyUpload">上传到服务器</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-upload ref="upload" :limit="1" :action="upload.url" :headers="upload.headers" :file-list="upload.fileList"
        :on-progress="handleFileUploadProgress" :on-success="handleAcceptSuccess" :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <!-- <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading"
          @click="submitUpload">上传到服务器</el-button> -->
        <!-- <div slot="tip" class="el-upload__tip">不超过500kb</div> -->
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listDuty, getDuty, delDuty, addDuty, updateDuty, selectOmDutyListTree } from "@/api/system/duty";
import { listDept } from "@/api/system/dept";
import { addAccept, listByDuty } from "@/api/system/accept";
import { addFile, listFile, delFile } from "@/api/system/file";
import { getToken } from "@/utils/auth";

export default {
  name: "Duty",
  dicts: ['sys_complete'],
  data() {
    return {
      userId: this.$store.state.user.id,
      name: '',
      deptList: [],
      categoryId: null,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      isAccept: false,
      acceptId: '',
      fileAcceptList: [],
      fileDutyList: [],
      duty: {},
      dutyId: null,
      dutyDescription: null,
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      uploadDuty: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      dutyList: [],
      dutyListOption: [],
      acceptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParamsFile: {
        deptId: ''
      },
      queryParams: {
        dateTime: [],
        parentId: 0,
        pageNum: 1,
        pageSize: 10,
        name: null,
        completeTime: null,
        enableMark: '0',
        dateTimeBefore: '',
        dateTimeAfter: '',
      },
      // 表单参数
      form: {
        parentId: 0,
        id: null,
        name: null,
        completeTime: null,
        enableMark: null,
        remark: null,
        file: [],
        deptIdList: []
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '任务名不能为空', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getList();
    // this.listByDuty();
    this.getListDept()
  },
  watch: {
    name(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
    setEnableMark(data) {
      var updateData = {
        id: data.id,
        enableMark: data.enableMark == '1' ? '0' : '1'
      }
      updateDuty(updateData).then(res => {

        this.getList();
        // this.listByDuty();
        this.getListDept()
      })
    },
    getListDept() {
      listDept().then(response => {
        this.deptList = response.data;
      });
    },
    //节点点击事件
    handleNodeClickDia(data, node, nodeData) {
      // if(data.isLeaf==1){
      // this.treeData= data.categoryName;
      this.categoryId = data.id;
      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectTree.blur();
      // }
    },
    handleNodeClick(data) {
      console.log(data);
    },
    acceptDuty(row) {
      this.$confirm('是否接受该任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var data = {
          dutyId: row.id
        }
        addAccept(data).then(res => {
          if (res.code == 200) {
            this.getList();
            this.$message({
              type: 'success',
              message: '接受成功!'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    downFile(row) {
      window.open(row.fileUrl)
    },
    handleDeleteFile(row) {
      delFile(row.id).then(res => {
        this.$message.success(res.msg);
        this.getList();
      })
    },
    searchFile() {
      this.selectFile(this.duty)
    },
    selectFile(row, column, event) {
      this.duty = row
      this.isAccept = row.accept
      this.dutyId = row.id
      this.acceptId = row.acceptId
      this.dutyDescription = row.remark
      var data = {
        dutyId: row.id,
        fileType: 'accept',
        deptId: this.queryParamsFile.deptId
      }
      // 任务文件
      listFile(data).then(res => {
        this.fileAcceptList = res.rows
      })
      // 相关附件
      data.fileType = "duty"
      listFile(data).then(res => {
        this.fileDutyList = res.rows
      })
    },
    handleAdd() {
      this.upload.fileList = [];
    },

    handleUpdate(row) {
      this.upload.fileList = [{ name: this.form.fileName, url: this.form.filePath }];
    },
    // 文件提交处理
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件提交处理
    submitDutyUpload() {
      this.$refs.uploadDuty.submit();
    },
    // 文件上传成功处理
    handleDutySuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.filePath = response.url;
      var formFile = {
        fileName: response.originalFilename,
        url: response.url,
        dutyId: this.dutyId
      }
      this.form.file.push(formFile)
      console.log(this.form.file)
      // this.uploadDuty.fileList = []
      // addFile(form).then(res => {
      //   debugger

      // })
      this.$message.success(response.msg);
    },
    handleRemove(file, fileList) {
      if (file.id) {
        delFile(file.id).then(res => {
          this.$message.success(res.msg);
        })
      }
      this.form.file = []
    },
    handleAcceptSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.filePath = response.url;
      var formFile = {
        fileName: response.originalFilename,
        fileUrl: response.url,
        dutyId: this.dutyId,
        fileType: "accept",
        acceptId: this.acceptId
      }
      // this.form.file.push(formFile)
      addFile(formFile).then(res => {
        if (res) {
          this.$message.success(response.msg);
          this.dialogVisible = false
          this.upload.fileList = []
          this.getList()
          this.selectFile(this.duty)
        }

      })
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.filePath = response.url;
      var form = {
        originalFilename: response.originalFilename,
        url: response.url,
      }
      this.form.file.push(form)
      // addFile(form).then(res => {

      // })
      this.$message.success(response.msg);
    },
    uploadFile() {
      this.dialogVisible = true
    },
    listByDuty() {
      listByDuty().then(response => {
        this.acceptList = response;
        if (response) {
          this.dutyList.forEach(e => {
            var accept = response.filter(v => { return v.dutyId == e.id });
            if (accept.length > 0) {
              e.acceptId = accept[0].id
              e.accept = true
            } else {
              e.accept = false
            }
          });
          console.log(this.dutyList)
        }
      });

    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;

      this.queryParams.dateTimeBefore = '1'
      this.queryParams.dateTimeAfter = "1"
      if (this.queryParams.dateTime) {
        this.queryParams.dateTimeBefore = this.queryParams.dateTime[0]
        this.queryParams.dateTimeAfter = this.queryParams.dateTime[1]
      } else {
        this.queryParams.dateTimeBefore = ''
        this.queryParams.dateTimeAfter = ''
      }
      // this.queryParams.dateTimeBefore='21312'
      selectOmDutyListTree(this.queryParams).then(response => {
        this.dutyList = response.rows;

        this.dutyListOption = JSON.parse(JSON.stringify(response.rows))
        var parent = { id: 0, name: '任务列表' }
        this.dutyListOption.push(
          parent
        )
        this.total = response.total;
        this.loading = false;
        this.listByDuty()
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        completeTime: null,
        enableMark: null,
        remark: null,
        file: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDuty(id).then(response => {
        this.form = response.data;

        this.uploadDuty.fileList = JSON.parse(JSON.stringify(this.form.file))
        this.open = true;
        this.title = "修改任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.formDia.validate(valid => {
        if (valid) {

          if (this.form.id != null) {
            // this.$refs.uploadDuty.submit();
            updateDuty(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDuty(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除').then(function () {
        return delDuty(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/duty/export', {
        ...this.queryParams
      }, `duty_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>